#include "TextProcessor.h"
#include <filesystem>
#include <system_error>

namespace fs = std::filesystem;

TextProcessor::TextProcessor() {}

TextProcessor::~TextProcessor() {}

bool TextProcessor::readJsonFile(const std::string& filePath) {
    std::ifstream file(filePath);
    if (!file.is_open()) {
        std::cerr << "Cannot open file: " << filePath << std::endl;
        return false;
    }

    try {
        file >> jsonData;
    } catch (const json::parse_error& e) {
        std::cerr << "JSON parsing error: " << e.what() << std::endl;
        return false;
    }

    std::cout << "Successfully read JSON file: " << filePath << std::endl;
    return true;
}

bool TextProcessor::processJsonContent() {
    try {
        // 只处理ActiveUnits格式的JSON
        if (jsonData.contains("ActiveUnits")) {
            processPlatforms(jsonData["ActiveUnits"]);
            return true;
        } else {
            std::cout << "No ActiveUnits data found in JSON file." << std::endl;
            return false;
        }
    } catch (const std::exception& e) {
        std::cerr << "Error processing JSON content: " << e.what() << std::endl;
        return false;
    }
}

void TextProcessor::processPlatforms(const json& platformsData) {
    std::string formattedPlatforms;
    std::set<std::string> detectedPlatformTypes; // 记录JSON中出现的所有平台类型

    try {
        // 只处理新的ActiveUnits格式
        if (platformsData.is_object()) {
            // 新格式：按类型组织的平台
            for (auto it = platformsData.begin(); it != platformsData.end(); ++it) {
                std::string platformType = it.key(); // 平台类型名称
                detectedPlatformTypes.insert(platformType);
                
                std::cout << "Processing platform type: " << platformType << std::endl;
                
                // 确保值是数组
                if (it.value().is_array()) {
                    for (const auto& platform : it.value()) {
                        try {
                            // 处理单个平台，传入类型
                            formattedPlatforms += processOnePlatform(platform, platformType);
                        } catch (const std::exception& e) {
                            std::cerr << "Error processing a platform of type " << platformType << ": " << e.what() << std::endl;
                            std::cerr << "Platform data: " << platform.dump(2) << std::endl;
                        }
                    }
                }
            }
        } else {
            std::cerr << "ActiveUnits data is not in expected format." << std::endl;
            return;
        }
        
        // 添加所有找到的平台类型声明
        std::string typeDeclarations;
        PlatformTypeManager& manager = PlatformTypeManager::getInstance();
        for (const auto& type : detectedPlatformTypes) {
            if (manager.hasPlatformType(type)) {
                typeDeclarations += manager.getPlatformTypeDeclaration(type) + "\n";
            }
        }
        
        if (!typeDeclarations.empty()) {
            formattedPlatforms = typeDeclarations + formattedPlatforms;
        }
        
        // 写入到平台文件
        writeToFolder("platforms", formattedPlatforms, "platform_data.txt");
    } catch (const std::exception& e) {
        std::cerr << "Error in processPlatforms: " << e.what() << std::endl;
    }
}

// 处理单个平台的方法
std::string TextProcessor::processOnePlatform(const json& platform, const std::string& platformType) {
    std::string result;
    
    // 提取ID，如果没有则生成默认值
    std::string id;
    if (platform.contains("ID")) {
        id = platform["ID"].get<std::string>();
    } else {
        id = "unknown";
    }
    
    // 平台头行 - 检查ID是否已经包含platformID-前缀
    if (id.find("platformID-") == 0) {
        // ID已经包含前缀，直接使用
        result += "platform " + id + " " + platformType + "\n";
    } else {
        // ID不包含前缀，添加前缀
        result += "platform platformID-" + id + " " + platformType + "\n";
    }
    
    // 添加位置信息
    double lat = 0.0, lon = 0.0;
    
    // 检查并获取Lat
    if (platform.contains("Lat")) {
        lat = platform["Lat"].is_string() ? 
              std::stod(platform["Lat"].get<std::string>()) : 
              platform["Lat"].get<double>();
    }
    
    // 检查并获取Lon
    if (platform.contains("Lon")) {
        lon = platform["Lon"].is_string() ? 
              std::stod(platform["Lon"].get<std::string>()) : 
              platform["Lon"].get<double>();
    }
    
    result += "   position   " + std::to_string(lat) + "n " + std::to_string(lon) + "e\n";
    
    // 添加side信息
    std::string color = "unknown";
    if (platform.contains("Side")) {
        color = platform["Side"].get<std::string>();
    }
    
    result += "   side " + color + "\n";
    
    // 添加heading信息（从CH字段获取）
    int heading = 0;
    if (platform.contains("CH")) {
        if (platform["CH"].is_string()) {
            try {
                // 处理字符串形式的角度值，确保它是一个有效的数字字符串
                std::string headingStr = platform["CH"].get<std::string>();
                if (!headingStr.empty()) {
                    heading = std::stoi(headingStr);
                }
            } catch (...) {
                // 转换失败，使用默认值
                std::cerr << "Warning: Failed to convert CH string value to number: " 
                          << platform["CH"].dump() << std::endl;
                heading = 0;
            }
        } else if (platform["CH"].is_number()) {
            heading = platform["CH"].get<int>();
        } else {
            std::cerr << "Warning: CH field is neither string nor number: " 
                      << platform["CH"].dump() << std::endl;
        }
    }
    
    result += "   heading " + std::to_string(heading) + " mil\n";
    
    // 添加结束标识
    result += "end_platform\n\n";
    
    return result;
}

bool TextProcessor::writeToFolder(const std::string& folder, const std::string& content, const std::string& filename) {
    // Build complete path
    std::string folderPath = "testAfsimproject/" + folder;
    
    // Ensure directory exists
    if (!ensureDirectoryExists(folderPath)) {
        return false;
    }
    
    // Create complete file path
    std::string filePath = folderPath + "/" + filename;
    
    // Write to file
    std::ofstream outFile(filePath);
    if (!outFile.is_open()) {
        std::cerr << "Cannot create file: " << filePath << std::endl;
        return false;
    }
    
    outFile << content;
    outFile.close();
    
    std::cout << "Successfully wrote file: " << filePath << std::endl;
    return true;
}

bool TextProcessor::ensureDirectoryExists(const std::string& path) {
    std::error_code ec;
    if (!fs::exists(path, ec)) {
        if (!fs::create_directories(path, ec)) {
            std::cerr << "Cannot create directory: " << path << " - " << ec.message() << std::endl;
            return false;
        }
    }
    return true;
} 